import React, {useState} from "react";
import {
  Tooltip,
  ActionIcon,
  Alert,
  Button,
  Group,
  ScrollArea,
  Stack,
  Text,
  Fieldset,
  Badge,
} from "@mantine/core";
import {
  IconCheck,
  IconDatabaseImport,
  IconLocationShare,
  IconMoodConfuzed,
  IconMoodWink,
  IconSlice,
} from "@tabler/icons-react";
import {modals} from "@mantine/modals";
import {Dropzone, DropzoneProps, MS_EXCEL_MIME_TYPE} from "@mantine/dropzone";

// 为规范代码，要求每个Modal中，都有一个私有的ModalContent，集中配置样式
const ModalContent: React.FC = (props: Partial<DropzoneProps>) => {
  const [formatOK, setFormatOK] = useState<null | boolean>(null); // 初始状态为 null 表示未校验
  const [loading, setLoading] = useState(false); // 加载状态
  const handleCheckFormat = async () => {
    setLoading(true);
    try {
      // 模拟后端返回结果
      const result = await new Promise<boolean>(
        (resolve) => setTimeout(() => resolve(Math.random() > 0.5), 1000), // 随机模拟校验结果
      );
      setFormatOK(result);
    } catch (error) {
      console.error("格式检查失败:", error);
      setFormatOK(false);
    } finally {
      setLoading(false);
    }
  };
  return (
    <Stack gap="xs">
      <Dropzone
        onDrop={(files) => {
          console.log("accepted files", files);
          handleCheckFormat(); // 模拟格式检查
        }}
        onReject={(files) => console.log("rejected files", files)}
        h={200}
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
        }}
        maxSize={5 * 1024 ** 2} // 文件大小限制
        accept={MS_EXCEL_MIME_TYPE} // 文件类型限制
        {...props}
      >
        <Stack align="center">
          <Dropzone.Idle>
            <IconDatabaseImport
              size={52}
              style={{color: "var(--mantine-color-dimmed)"}}
              stroke={1.5}
            />
          </Dropzone.Idle>
          <Dropzone.Accept>
            <IconMoodWink size={52} style={{color: "var(--mantine-color-blue-6)"}} stroke={1.5} />
          </Dropzone.Accept>
          <Dropzone.Reject>
            <IconMoodConfuzed
              size={52}
              style={{color: "var(--mantine-color-red-6)"}}
              stroke={1.5}
            />
          </Dropzone.Reject>

          <Stack gap={2} align="center" justify="center">
            <Text size="sm" inline>
              文件拖拽至此或点击此区域选取文件
            </Text>
            <Text size="xs" inline mt={7}>
              要求.xls/.xlsx格式，5MB以内
            </Text>
          </Stack>
        </Stack>
      </Dropzone>
      {/* 动态显示 Alert，三种状态：null/true/false */}
      {formatOK === true && (
        <Alert variant="light" color="green" title="格式检查通过" icon={<IconCheck />} />
      )}
      {formatOK === false && (
        <Alert variant="light" color="red" title="格式检查未通过" icon={<IconCheck />}>
          请检查文件格式并重试
        </Alert>
      )}
      <Group justify="flex-end">
        <Button variant="default" onClick={modals.closeAll}>
          取消
        </Button>
        <Button disabled={!formatOK} onClick={modals.closeAll}>
          上传
        </Button>
      </Group>
    </Stack>
  );
};

export const SliceConfig = ({disabled}: {disabled: boolean}) => {
  const [hasSliceInfo, setHasSliceInfo] = useState(true);
  return (
    <Tooltip
      label="切片配置"
      withArrow
      position="bottom"
      transitionProps={{transition: "fade", duration: 300}}
    >
      <ActionIcon
        variant="light"
        color="grape"
        disabled={disabled}
        onClick={() =>
          modals.open({
            title: "切片配置",
            children: (
              <Stack>
                <Fieldset legend="一、根据节点信息生成模板">
                  <Button
                    fullWidth
                    variant="light"
                    color="violet"
                    leftSection={<IconLocationShare size={16} />}
                  >
                    生成切片模板并导出
                  </Button>
                </Fieldset>
                <Fieldset legend="二、上传切片网络及流量需求">
                  <ModalContent />
                </Fieldset>
                <Fieldset legend="附：后台切片数据状态">
                  <Group justify="space-between">
                    <Badge variant="light" color={hasSliceInfo ? "green" : "gray"} size="lg">
                      {hasSliceInfo ? "切片信息已存在" : "切片信息不存在"}
                    </Badge>
                    <Group>
                      <Button
                        variant="light"
                        color="red"
                        // size="xs"
                        // leftSection={<IconTrash size={16} />}
                        disabled={!hasSliceInfo}
                      >
                        清除
                      </Button>
                      <Button
                        variant="light"
                        color="blue"
                        // size="xs"
                        // leftSection={<IconDownload size={16} />}
                        disabled={!hasSliceInfo}
                      >
                        下载
                      </Button>
                    </Group>
                  </Group>
                </Fieldset>
              </Stack>
            ),
            scrollAreaComponent: ScrollArea.Autosize,
          })
        }
      >
        <IconSlice size={16} />
      </ActionIcon>
    </Tooltip>
  );
};
